<template>
  <div class="screen-router">
    <!-- Header区域 -->
    <div class="screen-header">
      <div class="header-content">
        <div class="header-left">
          <h1>数据大屏路由系统</h1>
          <div class="connection-status">
            <el-tag :type="screenStore.isConnected ? 'success' : 'danger'">
              {{ screenStore.isConnected ? '已连接' : '未连接' }}
            </el-tag>
            <span class="current-page">当前页面: {{ screenStore.config.currentPage }}</span>
          </div>
        </div>
        <div class="header-right">
          <div class="screen-controls">
            <el-button 
              type="primary" 
              size="large"
              @click="toggleFullscreen"
              :icon="isFullscreen ? 'Close' : 'FullScreen'"
            >
              {{ isFullscreen ? '退出全屏' : '大屏模式' }}
            </el-button>
            <el-button 
              type="success" 
              size="large"
              @click="refreshPage"
              icon="Refresh"
            >
              刷新页面
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- Content区域 -->
    <div class="screen-content">
      <router-view />
    </div>

    <!-- 自动切换倒计时 -->
    <div v-if="screenStore.config.mode === 'auto'" class="auto-switch-timer">
      <div class="timer-label">自动切换倒计时</div>
      <div class="timer-value">{{ countdown }}s</div>
    </div>

    <!-- 页面切换指示器 -->
    <div class="page-indicator">
      <div class="indicator-dots">
        <div 
          v-for="(page, index) in screenStore.config.pages" 
          :key="page"
          class="dot"
          :class="{ active: screenStore.config.currentPage === page }"
          @click="switchToPage(page)"
        ></div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useScreenStore } from '../stores/screenStore'
import WebSocketService from '../utils/websocket'
import { ElMessage } from 'element-plus'

export default {
  name: 'ScreenRouter',
  setup() {
    const router = useRouter()
    const screenStore = useScreenStore()
    const countdown = ref(screenStore.config.interval)
    const isFullscreen = ref(false)
    let timer = null
    
    // 自动切换逻辑
    const startAutoSwitch = () => {
      if (screenStore.config.mode === 'auto') {
        timer = setInterval(() => {
          countdown.value--
          if (countdown.value <= 0) {
            // 切换到下一个页面
            const currentIndex = screenStore.config.pages.indexOf(screenStore.config.currentPage)
            const nextIndex = (currentIndex + 1) % screenStore.config.pages.length
            const nextPage = screenStore.config.pages[nextIndex]
            switchToPage(nextPage)
            countdown.value = screenStore.config.interval
          }
        }, 1000)
      }
    }
    
    const stopAutoSwitch = () => {
      if (timer) {
        clearInterval(timer)
        timer = null
      }
    }
    
    // 切换页面
    const switchToPage = (pageName) => {
      try {
        screenStore.switchPage(pageName)
        // 根据页面名称路由到对应的组件
        const routeMap = {
          '首页': '/screen/home',
          '数据概览': '/screen/overview',
          '实时监控': '/screen/monitor',
          '统计分析': '/screen/statistics',
          '系统设置': '/screen/settings'
        }
        
        const route = routeMap[pageName]
        if (route && router.currentRoute.value.path !== route) {
          router.push(route)
        }
        
        ElMessage.success(`页面已切换到: ${pageName}`)
      } catch (error) {
        ElMessage.error('页面切换失败')
      }
    }
    
    // 切换全屏模式
    const toggleFullscreen = () => {
      if (!isFullscreen.value) {
        const elem = document.documentElement
        if (elem.requestFullscreen) {
          elem.requestFullscreen()
        } else if (elem.webkitRequestFullscreen) {
          elem.webkitRequestFullscreen()
        } else if (elem.msRequestFullscreen) {
          elem.msRequestFullscreen()
        }
        isFullscreen.value = true
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        }
        isFullscreen.value = false
      }
    }
    
    // 刷新页面
    const refreshPage = () => {
      window.location.reload()
    }
    
    // 监听模式变化
    watch(() => screenStore.config.mode, (newMode) => {
      if (newMode === 'auto') {
        countdown.value = screenStore.config.interval
        startAutoSwitch()
      } else {
        stopAutoSwitch()
        countdown.value = screenStore.config.interval
      }
    })
    
    // 监听间隔时间变化
    watch(() => screenStore.config.interval, (newInterval) => {
      if (screenStore.config.mode === 'auto') {
        countdown.value = newInterval
      }
    })
    
    // 监听页面切换
    watch(() => screenStore.config.currentPage, (newPage) => {
      if (screenStore.config.mode === 'auto') {
        countdown.value = screenStore.config.interval
      }
      // 路由到对应页面
      switchToPage(newPage)
    })
    
    // 监听全屏状态变化
    const handleFullscreenChange = () => {
      isFullscreen.value = !!document.fullscreenElement
    }
    
    onMounted(async () => {
      // 监听全屏状态变化
      document.addEventListener('fullscreenchange', handleFullscreenChange)
      document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
      document.addEventListener('msfullscreenchange', handleFullscreenChange)
      
      // 连接WebSocket
      try {
        await WebSocketService.connect()
        screenStore.isConnected = true
        
        // 订阅配置更新
        WebSocketService.subscribe('/topic/screen-config', (message) => {
          if (message.type === 'config') {
            Object.assign(screenStore.config, message.data)
          }
        })
        
        // 订阅页面切换
        WebSocketService.subscribe('/topic/screen-switch', (message) => {
          if (message.type === 'switch') {
            screenStore.config.currentPage = message.data
          }
        })
        
        // 获取初始配置
        await screenStore.fetchConfig()
        
        // 启动自动切换
        if (screenStore.config.mode === 'auto') {
          startAutoSwitch()
        }
      } catch (error) {
        console.error('WebSocket连接失败:', error)
        screenStore.isConnected = false
      }
    })
    
    onUnmounted(() => {
      stopAutoSwitch()
      WebSocketService.disconnect()
      
      // 移除全屏监听器
      document.removeEventListener('fullscreenchange', handleFullscreenChange)
      document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
      document.removeEventListener('msfullscreenchange', handleFullscreenChange)
    })
    
    return {
      screenStore,
      countdown,
      isFullscreen,
      switchToPage,
      toggleFullscreen,
      refreshPage
    }
  }
}
</script>

<style scoped>
.screen-router {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  overflow: hidden;
}

.screen-header {
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: 15px 30px;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h1 {
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: bold;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 14px;
}

.current-page {
  opacity: 0.9;
}

.header-right {
  display: flex;
  align-items: center;
}

.screen-controls {
  display: flex;
  gap: 15px;
}

.screen-content {
  flex: 1;
  overflow: hidden;
  position: relative;
}

/* 自动切换倒计时 */
.auto-switch-timer {
  position: fixed;
  bottom: 30px;
  right: 30px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border-radius: 10px;
  padding: 15px 20px;
  text-align: center;
  border: 1px solid rgba(255, 255, 255, 0.2);
  z-index: 1000;
}

.timer-label {
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 5px;
}

.timer-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

/* 页面指示器 */
.page-indicator {
  position: fixed;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
}

.indicator-dots {
  display: flex;
  gap: 10px;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 10px 15px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
}

.dot:hover {
  background: rgba(255, 255, 255, 0.5);
  transform: scale(1.2);
}

.dot.active {
  background: #409eff;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

/* 全屏模式样式 */
:fullscreen .screen-header {
  padding: 10px 20px;
}

:fullscreen .screen-header h1 {
  font-size: 20px;
}

:fullscreen .screen-controls {
  gap: 10px;
}

:fullscreen .auto-switch-timer {
  bottom: 20px;
  right: 20px;
  padding: 10px 15px;
}

:fullscreen .page-indicator {
  bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 15px;
  }
  
  .screen-controls {
    flex-direction: column;
    gap: 10px;
  }
  
  .connection-status {
    flex-direction: column;
    gap: 5px;
  }
}
</style> 